package com.changgou.pay.controller;

import com.alibaba.fastjson.JSON;
import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.pay.config.RabbitMQConfig;
import com.changgou.pay.service.WXPayService;
import com.changgou.util.ConvertUtils;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zero
 * @date 2020/7/13
 */

@RestController
@RequestMapping("/wxpay")
public class WXPayController {

    @Autowired
    private WXPayService wxPayService;

    @GetMapping("/nativePay")
    public Result<Map> nativePay(@RequestParam("orderId")String orderId,@RequestParam("money")Integer money){

        Map map = wxPayService.nativePay(orderId, money);

        return new Result<>(true, StatusCode.OK,"",map);
    }

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @RequestMapping("/notify")
    public void notifyLogic(HttpServletRequest request , HttpServletResponse response){
        System.out.println("回调函数");

        try {
            //输出流转换为字符串
            String xml = ConvertUtils.convertToString(request.getInputStream());
            System.out.println(xml);

            //基于微信查询订单信息
            try {
                //1.解析xml
                Map<String, String> paramMap = WXPayUtil.xmlToMap(xml);
                //2.判单微信返回订单的支付状态
                if ("SUCCESS".equals(paramMap.get("result_code"))){
                    //微信返回的支付状态成功(以防篡改,需调用wxpay自带查询再去查一遍)
                    Map result = wxPayService.queryOrder(paramMap.get("out_trade_no"));
                    if ("SUCCESS".equals(result.get("result_code"))){
                        //代表二次查询成功,发送消息到rabbitmq
                        Map<String,String> map = new HashMap<>();
                        map.put("orderId",paramMap.get("out_trade_no"));
                        map.put("transactionId",paramMap.get("transaction_id"));
                        rabbitTemplate.convertAndSend( "", RabbitMQConfig.ORDER_PAY, JSON.toJSONString(map));

                        //完成双向通信
                        rabbitTemplate.convertAndSend("paynotify","",paramMap.get("out_trade_no"));
                    }

                    //给微信返回结果通知
                    response.setContentType("text/xml");
                    String data = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
                    response.getWriter().write(data);

                }else {
                    //打印错误信息
                    System.out.println(paramMap.get( "err_code_des" ));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @PutMapping("/close/{orderId}")
    public Result closeOrder(@PathVariable("orderId") String orderId){

        Map map = wxPayService.closeOrder(orderId);

        return new Result(true,StatusCode.OK,"关闭微信订单成功",map);

    }

    @GetMapping("/query/{orderId}")
    public Result queryOrder(@PathVariable("orderId") String orderId){
        Map map = wxPayService.queryOrder(orderId);

        return new Result(true,StatusCode.OK,"查询订单成功",map);
    }
}
